package com.thermoberg.zhousi.interceptor;

import com.thermoberg.zhousi.model.Message;
import com.thermoberg.zhousi.util.LoginToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor{

    @Autowired
    private LoginToken loginToken;


    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object o) throws Exception {
        res.setContentType("text/html;charset=UTF-8");
        Cookie [] cookies = req.getCookies();
        String token = "";
        if(cookies != null){
            for(Cookie cookie:cookies){
                //System.out.println(cookie.getName());
                if("token".equals(cookie.getName())){
                    token=cookie.getValue();
                }
            }
        }

        String requestType = req.getHeader("X-Requested-With");
        //System.out.println(req.getRequestURI() + " type:" + requestType)
        if("".equals(token)){
            //根据requestType字符串是否为空来判断是正常请求还是ajax请求
            if(requestType == null||requestType.trim().isEmpty()){
                res.sendRedirect("/toLogin");
                return false;
            }
            //ajax请求失败,返回一个状态码401给浏览器
            res.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }

        try {
            String[] userInfo = loginToken.getUserInfo(token);
            if (userInfo == null) {
                //登录过期,若是正常请求,直接重定向到登录页面
                if(requestType == null||requestType.trim().isEmpty()){
                    res.sendRedirect("/toLogin");
                    return false;
                }
                //ajax请求过期,返回一个状态码401给浏览器
                res.setStatus(HttpStatus.UNAUTHORIZED.value());
                return false;
            } else {
                req.setAttribute("admincode",userInfo[0] );
                return true;
            }
        } catch (Exception e) {
            res.sendRedirect("/toLogin");
            return false;

        }

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
